﻿using SeeSharpTools.JY.ArrayUtility;
using SeeSharpTools.JY.DSP.Fundamental;
using SeeSharpTools.JY.DSP.SoundVibration;
using Sunny.UI;
using System;

namespace SeeSharpTools.Demo
{
    public partial class FormHarmonicMeasure : UIPage
    {
        private bool isRunning = false;

        public FormHarmonicMeasure()
        {
            InitializeComponent();
        }

        private void uiSymbolButton_Click(object sender, EventArgs e)
        {
            if (isRunning)
            {
                timer1.Stop();
                uiSymbolButton.Symbol = 61515;
                isRunning = false;
            }
            else
            {
                timer1.Start();
                uiSymbolButton.Symbol = 61516;
                isRunning = true;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            textBox1.Clear();
            int dataLength = 4000;
            double[] signal = new double[dataLength];
            double[] noise = new double[dataLength];
            double[] spectrum = new double[dataLength / 2];
            double sampleRate = uiDoubleUpDown_SampleRate.Value;
            int highestHarmonic = uiIntegerUpDown_HighestOrder.Value;
            double[] harmonicsLevel = new double[highestHarmonic + 1];
            //产生方波信号和噪声信号，并叠加
            Generation.SquareWave(ref signal, uiDoubleUpDown_SignalAmp.Value, 50, uiDoubleUpDown_SignalFreq.Value, sampleRate);
            Generation.UniformWhiteNoise(ref noise, uiDoubleUpDown_NoiseAmp.Value);
            ArrayCalculation.Add(signal, noise, signal);

            easyChartX1.Plot(signal);
            //功率谱分析，使用默认的V2功率谱单位和汉宁窗
            Spectrum.PowerSpectrum(signal, sampleRate, ref spectrum, out double df, SpectrumUnits.dBV);
            easyChartX2.Plot(spectrum, 0, df);
            //各阶次频率分量以及THD计算，谐波分量数组中index0是DC，index1是基频，以此类推
            HarmonicAnalyzer.ToneAnalysis(signal, 1 / sampleRate, out double peakFrequency, out double THD, ref harmonicsLevel, highestHarmonic);
            for (int i = 1; i <= highestHarmonic; i++)
            {
                textBox1.AppendText(i.ToString("00") + ": " + harmonicsLevel[i].ToString("0.000") + "\r\n");
            }
        }
    }
}